import { NextRequest, NextResponse } from 'next/server';
import UserModel from '@/models/user';
import { authMiddleware, TokenPayload } from '@/utils/auth';

// GET /api/profile - 获取用户个人资料
export async function GET(request: NextRequest) {
  try {
    console.log('正在验证令牌');
    // 验证用户身份
    const authResult = await authMiddleware(request);
    if (authResult instanceof NextResponse) {
      return authResult; // 返回错误响应
    }
    
    const decoded = authResult as TokenPayload;
    const userId = decoded.id;
    
    // 获取用户资料
    const user = await UserModel.findById(userId);
    if (!user) {
      return NextResponse.json(
        { error: '用户不存在' },
        { status: 404 }
      );
    }
    
    // 移除敏感信息
    const { password, ...userWithoutPassword } = user;
    
    return NextResponse.json(
      userWithoutPassword,
      { status: 200 }
    );
    
  } catch (error) {
    console.error('获取用户资料错误:', error);
    return NextResponse.json(
      { error: '服务器错误，请稍后再试' },
      { status: 500 }
    );
  }
}

// PUT /api/profile - 更新用户个人资料
export async function PUT(request: NextRequest) {
  try {
    console.log('正在验证令牌');
    // 验证用户身份
    const authResult = await authMiddleware(request);
    if (authResult instanceof NextResponse) {
      return authResult; // 返回错误响应
    }
    
    const decoded = authResult as TokenPayload;
    const userId = decoded.id;
    
    // 获取请求数据
    const body = await request.json();
    console.log('更新用户资料请求:', body);
    console.log('收到的出生日期:', body.birth_date);
    console.log('收到的单位信息:', body.company);
    
    try {
      // 更新用户资料
      const updated = await UserModel.updateProfile(userId, body);
      
      if (!updated) {
        console.error('更新用户资料失败，未影响任何行');
        return NextResponse.json(
          { error: '更新用户资料失败' },
          { status: 400 }
        );
      }
      
      // 获取更新后的用户资料
      const user = await UserModel.findById(userId);
      console.log('更新后的用户资料:', user);
      
      // 移除敏感信息
      const { password, ...userWithoutPassword } = user as any;
      
      return NextResponse.json(
        { 
          message: '更新用户资料成功',
          user: userWithoutPassword 
        },
        { status: 200 }
      );
    } catch (updateError) {
      console.error('更新过程中发生错误:', updateError);
      return NextResponse.json(
        { error: `更新资料时发生错误: ${(updateError as Error).message}` },
        { status: 500 }
      );
    }
  } catch (error) {
    console.error('更新用户资料错误:', error);
    return NextResponse.json(
      { error: '服务器错误，请稍后再试' },
      { status: 500 }
    );
  }
} 